package com.jnzc.ocr.serv.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;
import com.jnzc.ocr.dependencies.serv.mybatis.MybatisServiceImpl;
import com.jnzc.ocr.serv.system.entity.SysRegion;
import com.jnzc.ocr.serv.system.filter.SysRegionFilter;
import com.jnzc.ocr.serv.system.mapper.SysRegionMapper;
import com.jnzc.ocr.serv.system.service.SysRegionService;
import com.jnzc.ocr.serv.system.vo.SysRegionVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author zhangcm
 * @version 1.0, 2017-10-15
 */
@Service
public class SysRegionServiceImpl extends MybatisServiceImpl<SysRegionMapper, SysRegion, SysRegionFilter> implements SysRegionService {

    @Override
    protected void fillEntityWrapper(EntityWrapper<SysRegion> ew, SysRegionFilter filter) {
        SysRegion entity = new SysRegion();
        entity.setShow(filter.getShow());
        ew.setEntity(entity);
        if(null != filter.getMaxLevel()) {
            ew.le("level", filter.getMaxLevel());
        }
    }

    @Override
    public List<SysRegionVo> list(Integer maxLevel) {
        SysRegionFilter filter = new SysRegionFilter();
        filter.setMaxLevel(maxLevel);
        filter.setShow(true);
        List<SysRegion> list = super.list(filter);
        return createTreeList(list, null);
    }

    private List<SysRegionVo> createTreeList(List<SysRegion> list, String parentCode) {
        List<SysRegionVo> result = Lists.newArrayList();
        List<SysRegion> tempList = Lists.newArrayList();
        for (SysRegion obj : list) {
            if(Objects.equals(parentCode, obj.getParentCode())){
                SysRegionVo vo = new SysRegionVo();
                if(StringUtils.isNotEmpty(obj.getShowName())) {
                    vo.setName(obj.getShowName());
                }else{
                    vo.setName(obj.getName());
                }
                vo.setCode(obj.getCode());
                result.add(vo);
                tempList.add(obj);
            }
        }
        list.removeAll(tempList);
        for (SysRegionVo vo : result) {
            List<SysRegionVo> childList = createTreeList(list, vo.getCode());
            vo.setList(childList);
        }
        return result;
    }
}
